//
//  CameramanTimeViewController.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 10/13/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "CameramanTimeViewController.h"

#import "CameramanTimeCell.h"

@interface CameramanTimeViewController ()
{
    UIButton * preMonthBtn;
    UIButton * nextMonthBtn;
    
    UILabel * monthLB;  //显示月份
    UIButton * monthButton; //下一月按钮
    
    NSDate * startDate;
    NSDate * lastDate;
    NSDateComponents * startComps;
    NSDateComponents * lastComps;
    
    NSInteger startIndex;
    

}
@end

@implementation CameramanTimeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.titleLabel.text = @"摄影师时间表";
    self.dayArray = [[NSMutableArray alloc] init];
    self.dayArray1 = [[NSMutableArray alloc] init];
    self.dayArray2 = [[NSMutableArray alloc] init];
    [self initViews];
    
}

#pragma mark
#pragma mark UI 布局
-(void)initViews
{
    CGFloat cheight= iPhone5?0:25;
    //本月
    preMonthBtn = [UIButton initButton:CGRectMake(160-75, (68-15)/2.0f-cheight, 75, 30) btnImage:nil btnTitle:@"9月"];
    [preMonthBtn setTitleColor:UIColorFromRGB(0x453d35) forState:UIControlStateNormal];
    [preMonthBtn setTitleColor:UIColorFromRGB(0xffb619) forState:UIControlStateDisabled];
    [preMonthBtn addTarget:self action:@selector(monthBtnCilck:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:preMonthBtn];
    
    //下一月
    nextMonthBtn = [UIButton initButton:CGRectMake(160, preMonthBtn.frame.origin.y, 75, 30) btnImage:nil btnTitle:@"9月"];
    [nextMonthBtn setTitleColor:UIColorFromRGB(0x453d35) forState:UIControlStateNormal];
    [nextMonthBtn setTitleColor:UIColorFromRGB(0xffb619) forState:UIControlStateDisabled];
    [nextMonthBtn addTarget:self action:@selector(monthBtnCilck:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:nextMonthBtn];
    
    preMonthBtn.enabled = NO;
    
    //星期
    NSArray * weekArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    for (int i = 0; i <7;i++){
        UILabel * lb = [UILabel initLabelText:[weekArray objectAtIndex:i] andRect:CGRectMake(6+44*i,height_y(nextMonthBtn), 44, 106/2.0f-cheight) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:14] andTextColor:UIColorFromRGB(0x453d35) andTextAlignment:NSTextAlignmentCenter];
        if (i == 0||i==6){
            lb.textColor = UIColorFromRGB(0xb6b6b6);
        }
        [self.contentView addSubview:lb];
    }

    [self initDayCollectionViews:height_y(nextMonthBtn)+106/2.0f-cheight view:nil];
    
    [self getDayDatas];

}

-(void)initDayCollectionViews:(CGFloat)height view:(UIView *)view
{
    UICollectionViewFlowLayout * dayflowLayout = [[UICollectionViewFlowLayout alloc] init];
    dayflowLayout.minimumInteritemSpacing =0;
    dayflowLayout.minimumLineSpacing =0;
    [dayflowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    dayCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(6,height, UI_SCREEN_WIDTH-12, 6*118/2.0f) collectionViewLayout:dayflowLayout];
    [dayCollectionView registerClass:[CameramanTimeCell class] forCellWithReuseIdentifier:@"dayCell"];
    dayCollectionView.backgroundColor = [UIColor clearColor];
    dayCollectionView.bounces = NO;
    dayCollectionView.alwaysBounceVertical = YES;
    dayCollectionView.delegate = self;
    dayCollectionView.dataSource = self;
    [self.contentView addSubview:dayCollectionView];
    
    
    
}

#pragma mark
#pragma mark 选择月份
-(void)monthBtnCilck:(UIButton *)button
{
    preMonthBtn.enabled = button == preMonthBtn?NO:YES;
    nextMonthBtn.enabled = button == nextMonthBtn?NO:YES;
    
    if (button ==preMonthBtn){
        _dayArray = _dayArray1;
    }else{
        _dayArray = _dayArray2;
    }
    [dayCollectionView reloadData];
}

#pragma mark
#pragma mark UICollcitonView Delegate
//设置分区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个分区上的元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_dayArray count];
}

//设置元素内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identify = @"dayCell";
    CameramanTimeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    
    
    cell.bgView.hidden = NO;
    cell.timeLB.text = @"全天";
    cell.disEnableLB.hidden = YES;
    cell.contentLB.enabled =YES;
    cell.contentLB.textColor = UIColorFromRGB(0x453d35);
    
    if ([[_dayArray objectAtIndex:indexPath.row] isKindOfClass:[NSString class]]){
        cell.contentLB.text =@"";
        cell.contentLB.enabled = NO;
        cell.bgView.hidden = YES;
        cell.disEnableLB.hidden = YES;
        return cell;
    }
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents * comps;
    comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:[_dayArray objectAtIndex:indexPath.row]];
    if ([comps month]==[startComps month]){
        if ([lastComps month]!=[startComps month]){
            if ([comps day]>=[startComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
                NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
                for (NSDictionary * ddcc in self.busyTimeArray){
                    [dateFormat setDateFormat:@"yyyy-MM-dd"];
                    NSString *  s = [dateFormat stringFromDate:[_dayArray objectAtIndex:indexPath.row]];
                    
                    if ([[ddcc valueForKey:@"ShootDate"] isEqualToString:s]){
                        if ([ddcc[@"ShootType"] isEqualToString:@"AM"]){
                            if ([cell.timeLB.text isEqualToString:@"上午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"下午";
                            }

                        }else if ([ddcc[@"ShootType"] isEqualToString:@"PM"]){
                            if ([cell.timeLB.text isEqualToString:@"下午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"上午";
                            }
                        }
                    }
                }
            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;
                cell.bgView.hidden = YES;
                cell.disEnableLB.hidden = YES;
                
            }
        }else{
            if ([comps day]>=[startComps day]&&[comps day]<=[startComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
                NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
                for (NSDictionary * ddcc in self.busyTimeArray){
                    [dateFormat setDateFormat:@"yyyy-MM-dd"];
                    NSString *  s = [dateFormat stringFromDate:[_dayArray objectAtIndex:indexPath.row]];
           
                    if ([[ddcc valueForKey:@"ShootDate"] isEqualToString:s]){
                        if ([ddcc[@"ShootType"] isEqualToString:@"AM"]){
                            if ([cell.timeLB.text isEqualToString:@"上午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"下午";
                            }
                            
                        }else if ([ddcc[@"ShootType"] isEqualToString:@"PM"]){
                            if ([cell.timeLB.text isEqualToString:@"下午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"上午";
                            }
                        }
                    }
                }

            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;
                cell.bgView.hidden = YES;
                cell.disEnableLB.hidden = YES;
                
            }
        }
    }
    else if ([comps month] == [lastComps month]){
        if ([lastComps month]!=[startComps month]){
            if ([comps day]<=[lastComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
                NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
                for (NSDictionary * ddcc in self.busyTimeArray){

                    [dateFormat setDateFormat:@"yyyy-MM-dd"];
                    NSString *  s = [dateFormat stringFromDate:[_dayArray objectAtIndex:indexPath.row]];
                    
        
                    
                    if ([[ddcc valueForKey:@"ShootDate"] isEqualToString:s]){
                        DDLOG(@"s = %@",s);
                        if ([ddcc[@"ShootType"] isEqualToString:@"AM"]){
                            if ([cell.timeLB.text isEqualToString:@"上午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"下午";
                            }
                            
                        }else if ([ddcc[@"ShootType"] isEqualToString:@"PM"]){
                            if ([cell.timeLB.text isEqualToString:@"下午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"上午";
                            }
                        }
                    }
                }

            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;
                cell.bgView.hidden = YES;
                cell.disEnableLB.hidden = YES;
            }
        }else{
            if ([comps day]>=[startComps day]&&[comps day]<=[startComps day]){
                cell.contentLB.textColor = UIColorFromRGB(0x453d35);
                NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
                for (NSDictionary * ddcc in self.busyTimeArray){
                  
                    [dateFormat setDateFormat:@"yyyy-MM-dd"];
                    NSString *  s = [dateFormat stringFromDate:[_dayArray objectAtIndex:indexPath.row]];
                    
    
                    if ([[ddcc valueForKey:@"ShootDate"] isEqualToString:s]){
                        if ([ddcc[@"ShootType"] isEqualToString:@"AM"]){
                            if ([cell.timeLB.text isEqualToString:@"上午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"下午";
                            }
                            
                        }else if ([ddcc[@"ShootType"] isEqualToString:@"PM"]){
                            if ([cell.timeLB.text isEqualToString:@"下午"]){
                                cell.bgView.hidden = YES;
                                cell.disEnableLB.hidden = NO;
                            }else{
                                cell.bgView.hidden = NO;
                                cell.disEnableLB.hidden = YES;
                                cell.timeLB.text = @"上午";
                            }
                        }
                    }
                }
                
            }else{
                cell.contentLB.textColor = [UIColor lightGrayColor];
                cell.contentLB.enabled = NO;
                cell.bgView.hidden = YES;
                cell.disEnableLB.hidden = YES;
            }
        }
    }
    cell.contentLB.text = [NSString stringWithFormat:@"%d",[comps day]];
    
    return cell;

    
}

//设置元素的的大小框
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets top ={0,0,0,0};
    return top;
}

//设置顶部的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={0,0};
    return size;
}

//设置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    return CGSizeMake(44, 118/2.0f);
}

-(void)getDayDatas
{
    NSMutableArray * timeAarry = [[NSMutableArray alloc] init];
    
    NSDate * now = [NSDate date];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents * comps;
    comps = [calendar components:(NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
    
    int tmp = [comps day];
    for (int i =tmp-1;i>=0;i--){
        [comps setDay:-i];
        [comps setHour:0];
        [comps setMinute:0];
        [comps setSecond:0];
        
        NSDate * nowDate = [calendar dateByAddingComponents:comps toDate:now options:0];
        [timeAarry addObject:nowDate];
        
    }
    
    for (int i =1;i <=33;i++){
        [comps setDay:+i];
        [comps setHour:0];
        [comps setMinute:0];
        [comps setSecond:0];
        NSDate * nowDate = [calendar dateByAddingComponents:comps toDate:now options:0];
        
        [timeAarry addObject:nowDate];
        if (i == 3){
            startDate = nowDate;
            NSCalendar *jcalendar = [NSCalendar currentCalendar];
            NSDateComponents * jcomps;
            jcomps = [jcalendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:startDate];
            [preMonthBtn setTitle:[NSString stringWithFormat:@"%d月",[jcomps month]] forState:UIControlStateNormal];
            [preMonthBtn setTitle:[NSString stringWithFormat:@"%d月",[jcomps month]] forState:UIControlStateDisabled];
        }
        if (i == 33){
            lastDate = nowDate;
            NSCalendar *jcalendar = [NSCalendar currentCalendar];
            NSDateComponents * jcomps;
            jcomps = [jcalendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:lastDate];
            [nextMonthBtn setTitle:[NSString stringWithFormat:@"%d月",[jcomps month]] forState:UIControlStateNormal];
            [nextMonthBtn setTitle:[NSString stringWithFormat:@"%d月",[jcomps month]] forState:UIControlStateDisabled];
        }
    }
    
    
    NSCalendar *lcalendar = [NSCalendar currentCalendar];
    NSDateComponents *lcomps;
    lcomps = [lcalendar components:(NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[timeAarry lastObject]];
    
    NSDate * ldate = [timeAarry lastObject];
    
    NSDateComponents * tcomps;
    tcomps = [lcalendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[timeAarry lastObject]];
    
    int a = [self countOfDayInYear:[tcomps year] month:[tcomps month]];
    
    for (int i = 1;i<=a-[tcomps day];i++){
        [lcomps setDay:+i];
        [lcomps setHour:0];
        [lcomps setMinute:0];
        [lcomps setSecond:0];
        NSDate * nowDate = [lcalendar dateByAddingComponents:lcomps toDate:ldate options:0];
        [timeAarry addObject:nowDate];
    }
    
    [_dayArray1 removeAllObjects];
    [_dayArray2 removeAllObjects];
    
    startComps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:startDate];
    lastComps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:lastDate];
    
    
    comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
    for (int i = 0;i<[timeAarry count];i++){
        NSCalendar *dcalendar = [NSCalendar currentCalendar];
        NSDateComponents *dcomps;
        dcomps = [dcalendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[timeAarry objectAtIndex:i]];
        
        if ([dcomps year]==[comps year]&& [dcomps month]==[comps month]){
            [_dayArray1 addObject:[timeAarry objectAtIndex:i]];
        }
        if ([dcomps year] == [lastComps year]&&[dcomps month]==[lastComps month]){
            [_dayArray2 addObject:[timeAarry objectAtIndex:i]];
        }
    }
    
    comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:[timeAarry firstObject]];
    
    for (int i=1;i<[comps weekday];i++){
        [_dayArray1 insertObject:@"" atIndex:0];
    }
    
    comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit|NSWeekdayCalendarUnit) fromDate:[timeAarry objectAtIndex:[timeAarry count]-a]];
    for (int i = 1;i<[comps weekday];i++){
        [_dayArray2 insertObject:@"" atIndex:0];
    }
    
    _dayArray = _dayArray1;
    [dayCollectionView reloadData];
}


//判断一个月有多少天
-(int)countOfDayInYear:(int)year month:(int)month
{
    int day=0;
    switch(month)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day=31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day=30;
            break;
        case 2:
            if( (year%4==0 &&(year%100)!=0)||year%400==0)
                day = 28;
            else
                day =29;
            break;
        default :
            break;
    }
    return day;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
